<template>
    <div class="study_list_container">
        <div class="study_list">
            <div class="actions">
                <label>选择学生：</label>
                <select v-model="selectedStudentId">
                    <option v-for="student in student_list" :key="student.student_id" :value="student.student_id">{{
                        student.name }}
                    </option>
                </select>
                <button @click="addTaskToStudents">加入学习</button>
            </div>
            <table>
                <thead>
                    <tr>
                        <th><input type="checkbox" v-model="selectAll" @change="toggleSelectAll" /> 全选</th>
                        <th>序号</th>
                        <th>标题</th>
                        <th>类型</th>
                        <th>难度</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="content in contents" :key="content.id">
                        <td><input type="checkbox" v-model="selectedContents" :value="content.content_id" /></td>
                        <td>{{ content.content_id }}</td>
                        <td>{{ content.title }}</td>
                        <td>{{ content.type }}</td>
                        <td>{{ getGradeLevel(content.difficulty) }}</td>
                        <!-- 修改contents中的difficulty属性，是1就设置为一年级，2就设置为二年级，以此类推，直达6年纪 -->

                        <td class="action-buttons">
                            <button @click="viewContent(content.content_id)">查看</button>
                        </td>
                    </tr>
                </tbody>
            </table>

            <!-- 分页组件 -->
            <div class="pagination">
                <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
                <span>第 {{ currentPage }} 页 / 共 {{ pagination.total_pages }} 页</span>
                <button @click="nextPage" :disabled="currentPage === pagination.total_pages">下一页</button>
            </div>
        </div>

        <!-- 查看模态框 -->
        <el-dialog v-model="viewDialogVisible" :title="content.title || '内容详情'" width="50%" @close="closeViewModal">
            <div class="content-detail">
                <el-descriptions :column="1">
                    <el-descriptions-item label="内容">{{ content.text }}</el-descriptions-item>
                    <el-descriptions-item label="拼音">{{ content.pinyin || '无' }}</el-descriptions-item>
                    <el-descriptions-item label="翻译">{{ content.translation }}</el-descriptions-item>
                    <el-descriptions-item label="类型">
                        <el-tag :type="getContentTypeTag(content.type)">{{ content.type }}</el-tag>
                    </el-descriptions-item>
                </el-descriptions>
            </div>

            <template #footer>
                <el-button @click="closeViewModal">关闭</el-button>
            </template>
        </el-dialog>

    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { ApiService } from '@/api/apiService';
import { useUserStore } from '@/stores/user';


import {
    ElDialog,
    ElButton,
    ElMessage
} from 'element-plus'


const contents = ref([]);
const pagination = ref({});
// 分页相关状态
const currentPage = ref(1);
const pageSize = ref(10); // 每页显示 20 条数据
const content = ref({});
const viewDialogVisible = ref(false)
const userStore = useUserStore();
const student_list = ref([])
const student_ids = ref([])
const selectedStudentId = ref(1);
async function loadStudent() {
    const userId = userStore.getUser?.user_id;
    const response = await ApiService.getStudentsList(userId);
    student_list.value = response.data.data;
    student_ids.value = response.data.data.map(student => student.student_id);

    // 设置默认选中第一个学生
    if (student_list.value.length > 0) {
        selectedStudentId.value = student_list.value[0].student_id;
    }
}
watch(selectedStudentId, (newVal) => {
    if (newVal) {
        currentPage.value = 1
        fetchContents();
    }
})
const getGradeLevel = (difficulty) => {
    const gradeLevels = ['一年级', '二年级', '三年级', '四年级', '五年级', '六年级'];
    return gradeLevels[difficulty - 1] || difficulty;
}
const addTaskToStudents = async () => {

    // 获取选中的内容
    const selectedContentIds = selectedContents.value;
    const studentId = selectedStudentId.value;
    console.log("selectedContentIds:", selectedContentIds)
    if (selectedContentIds.length === 0) {
        ElMessage.error('请选择学习内容');
        return;
    } else {
        ApiService.generate_tasks(studentId, selectedContentIds)
            .then(response => {
                console.log("生成任务成功:", response)
                fetchContents()
                ElMessage.success('添加成功')
            })
            .catch(error => {
                ElMessage.error('添加失败，系统繁忙，请稍后再试')
            })
    }

}

async function fetchContents() {
    try {
        const response = await ApiService.getContents_study(currentPage.value, pageSize.value, selectedStudentId.value);
        contents.value = response.data.data.contents;
        pagination.value = response.data.data.pagination;
    } catch (error) {
        console.error('Error fetching contents:', error);
    }
}


// 初始化时加载数据
onMounted(async () => {
    await loadStudent();
    await fetchContents();
});
// 关闭查看模态框
const closeViewModal = () => {
    viewDialogVisible.value = false
};


// 查看学习内容
const viewContent = async (content_id) => {
    const response = await ApiService.get_content_by_id(content_id)
    console.log("response：", response)
    if (response.status === 200) {
        content.value = response.data.data
        viewDialogVisible.value = true
    } else {
        ElMessage.error(response.data.msg || '获取内容失败')
    }

}


// 内容类型标签样式
const getContentTypeTag = (type) => {
    const map = {
        '诗词': 'success',
        '文章': 'warning',
        '词汇': 'primary'
    }
    return map[type] || 'info'
}

// 上一页
const prevPage = () => {
    if (currentPage.value > 1) {
        currentPage.value--;
        fetchContents(); // 重新加载数据
    }
};

// 下一页
const nextPage = () => {
    if (currentPage.value < pagination.value.total_pages) {
        currentPage.value++;
        fetchContents(); // 重新加载数据
    }
};

// 选中的内容ID列表
const selectedContents = ref([]);

// 全选状态
const selectAll = ref(false);

// 全选/取消全选
const toggleSelectAll = () => {
    if (selectAll.value) {
        // 使用 map 方法将 contents 中的所有 content_id 添加到 selectedContents
        selectedContents.value = contents.value.map(content => content.content_id);
    } else {
        selectedContents.value = [];
    }
};

</script>

<style scoped>
    @import url("@/assets/css/study_list.css");
</style>